<script lang="tsx" setup>
import HelpImg from '../assets/help.png';
import IndicatorSource from '@/components/indicator-source/index.vue';
import message from 'vc/src/common/message';
import type { IColumnsOption } from 'vc';
import { formatMoneyValue } from '@/utils';
import TimeDetail from './time-detail.vue';
interface Props {
  /** 接口details数据 */
  detailsData: any[] | null;
  /** 年份表头数据 */
  yearsData?: number[];
  /** 加载 */
  loading?: boolean;
  /** 公司类型 */
  companyType?: number;
  /** 是否有母公司数据 */
  hasParentCompanyData?: boolean;
  /** 公司治理指标页面 */
  isSocialGovernance?: boolean;
}

const { detailsData = [], yearsData, companyType, loading, hasParentCompanyData, isSocialGovernance } = defineProps<Props>();

const emit = defineEmits(['change', 'update:companyType']);

let columns = $ref<IColumnsOption[]>([]);
let tableData = $ref<any[]>([]);

watch(
  [() => detailsData, () => yearsData],
  () => {
    formateTableData();
  },
  { immediate: true }
);

function formateTableData() {
  tableData = [];
  columns = [];

  columns.push(
    {
      title: '指标',
      fixed: 'left',
      width: 200,
      slots: {
        default: ({ row }) => {
          const _name = row.name;
          // 第一层大标题
          if (row.level === 1) {
            return (
              <>
                <div class="title">{_name}</div>
              </>
            );
          }
          // 小标题
          else if (row.level === 2) {
            return <div class="sub-title">{_name}</div>;
          }
          return (
            <>
              {row.helpIcon && row.annotation ? <img class="helpIcon" src={HelpImg} /> : null}
              <span onClick={() => toDetail(row)}>{_name}</span>
            </>
          );
        }
      }
    },
    {
      title: '单位',
      align: 'right',
      width: 120,
      field: 'unit'
    }
  );

  yearsData?.forEach((item) => {
    columns.push({
      title: item + '年',
      align: 'right',
      width: 150,
      slots: {
        default({ row }) {
          if ([1, 2].includes(row?.level)) {
            return '';
          }

          const data = row?.values?.filter((subItem) => {
            return subItem.year === item;
          });

          const _data = data?.[0];
          const _dataValue = _data?.value;
          const _value = _dataValue ? formatMoneyValue(_dataValue) : '-';
          const showJump = _dataValue && ((isTraceSource.value && _data?.fileUrl) || _data?.calcIndicatorRemark || _data?.contentDescription);
          const hasRemark = _dataValue && (_data?.calcIndicatorRemark || _data?.contentDescription) && _data?.notAddStar !== 1;

          return (
            <div class={[{ sourceLink: isTraceSource.value && _dataValue && _data?.fileUrl }, { hasRemark: hasRemark }]}>
              {showJump ? (
                <span style="cursor:pointer" onClick={() => goSource(_data)}>
                  {_value}
                </span>
              ) : (
                <span>{_value}</span>
              )}
            </div>
          );
        }
      }
    });
  });

  detailsData?.forEach((mainItem, index) => {
    tableData.push({
      name: mainItem.classificationLevel2,
      unit: ' ',
      level: 1,
      sort: index
    });
    mainItem?.secondClassificationDetails.forEach((item) => {
      // 只有一级副标题的不 push 进去
      if (mainItem?.classificationLevel === 3) {
        tableData.push({
          name: item.classificationLevel3,
          unit: ' ',
          level: 2
        });
      }

      item.thirdClassificationDetails?.forEach((subItem) => {
        tableData.push(subItem);
      });
    });
  });
}

const OPTIONS = ref([
  { name: '集团公司', code: 1 },
  { name: '本公司', code: 2 }
]);

const companyTypeRef = ref();
const handleChange = (val) => {
  if (val === companyType) return;

  if (!hasParentCompanyData) {
    const tips = val === 1 ? '集团公司' : '母公司';

    message.warning({
      message: `本公司暂未披露${tips}口径的环境绩效数据`,
      duration: 2000
    });
    companyTypeRef.value.selectValue = companyType;
  } else {
    emit('update:companyType', val);
  }
};

// 溯源开关
const isTraceSource = ref(false);
// 溯源弹窗
const showActionsheet = ref(false);
// 溯源弹窗数据
const actionData = ref<Record<string, any>>({});
// 溯源弹窗标题
const actionSheetTitle = ref('指标溯源');

// 溯源弹窗打开
function goSource(item) {
  actionSheetTitle.value = item.notAddStar === 1 ? item.indicator : '指标溯源';
  actionData.value = item;
  showActionsheet.value = true;
}

// 详情时间轴是否显示
let timeDetailShow = $ref(false);
// 当前点击的指标列
const currentDetail = ref();
const currentDetailName = ref();
// 点击左侧列 查看详情图表
function toDetail(item) {
  if (item?.historicalTrend && item?.values?.length) {
    currentDetailName.value = item.name;
    timeDetailShow = true;
    currentDetail.value = item;
  }
}

/** 主要指标 */
const isKeyIndicators = ref(false);
const onChange = (val) => {
  emit('change', val);
};
</script>

<template>
  <div class="container">
    <div class="filters">
      <vc-single-select v-if="!!companyType" ref="companyTypeRef" :value="companyType" title="数据归属" :options="OPTIONS" required @submit="handleChange" />
      <div v-if="!isSocialGovernance" class="text-switch">
        <span>主要指标</span> 
        <el-switch v-model="isKeyIndicators" size="small" style="--el-switch-on-color: #02C680" @change="onChange" />
      </div>
      <div class="text-switch">
        <span>数据溯源</span> 
        <el-switch v-model="isTraceSource" size="small" style="--el-switch-on-color: #02C680" />
      </div>
    </div>
    <vc-table :maxHeight="500" :loading="loading" :tableData="tableData" :columns="columns" />
    <time-detail v-if="timeDetailShow" v-model:show="timeDetailShow" :currentName="currentDetailName" :detail="currentDetail" @close="timeDetailShow = false" />
    <indicator-source v-model:show="showActionsheet" :actionData="actionData" :title="actionSheetTitle" />
  </div>
</template>
<style lang="scss" scoped>
.filters {
  font-size: 12px;
  line-height: 22px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 20px;
  .text-switch {
    color: #666666;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    column-gap: 5px;
  }
}

.container {
  :deep(.vc-table) {
    .title {
      font-weight: 600;
      font-size: 13px;
      line-height: 22px;
    }
    .sub-title {
      font-weight: 400;
      font-size: 13px;
      line-height: 22px;
      color: #ff7400;
    }
    .helpIcon {
      width: 12px;
      height: 12px;
      padding-right: 3px;
      margin-left: 0;
    }
  }
}
</style>
